//
//  PTReadSchedule.swift
//  PointTest28
//
//  Created by sc-chen on 2023/6/27.
//

import SwiftUI
import EventKit

struct PTReadSchedule: View {
    @State private var isShowingHUD = false
    @State private var detailTxt = "不支持开发功能"
    @State private var content = "读取日程表"
    @State private var eventStore = EKEventStore()
    @State private var pt_events: [[String : String]] = [
        //["date":"2023-08-10 星期四","eventName":"今日日程"],
    ]
    
    var body: some View {
        ZStack {
            VStack {
                if pt_events.count == 0 {
                    Button {
                        readEvents()
                    } label: {
                        Text(content)
                            .font(.system(size: 13))
                            .padding(EdgeInsets(top: 10, leading: 40, bottom: 10, trailing: 40))
                            .foregroundColor(.blue)
                            .overlay(
                                RoundedRectangle(cornerRadius: 10)
                                    .stroke(Color.blue, lineWidth: 1)
                                    .padding(.trailing,5)
                            )
                    }
                    .buttonStyle(.plain)
                    .padding()
                }else{
                    List(Array(pt_events.enumerated()), id: \.element) { idx,dict in
                        HStack {
                            VStack(alignment: .leading) {
                                Text("\(dict["date"] ?? "")")
                                    .font(.system(size: 12))
                                    .padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 5))
                                Text("\(dict["eventName"] ?? "")")
                                    .font(.system(size: 12))
                                    .padding((EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 5)))
                            }
                        }
                    }
                }
                Spacer()
            }
            PTProgressHud(isPresented: $isShowingHUD, text: $detailTxt)
        }
    }
    
    private func readEvents(){
        
        eventStore.requestAccess(to: .event) { granted, error in
            if granted {
                let predicate = eventStore.predicateForEvents(withStart: getLastDay(), end: Date.distantFuture, calendars: nil)
                let events = eventStore.events(matching: predicate)
                
                for event in events {
                    if !event.isAllDay {
                        pt_events.append(["date":"\(date2String(event.startDate)) \(weekdayStringFromDate(currentDate: event.startDate))","eventName":event.title])
                    }else{
                        content = "暂无数据"
                    }
                }
            } else {
                showHud()
            }
        }
    }
    
    
    func date2String(_ date:Date, dateFormat:String = "yyyy-MM-dd") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: date)
        return date
    }
    func weekdayStringFromDate(currentDate: Date) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current
        dateFormatter.dateFormat = "yyyy-MM-dd"
        guard let formatDate = dateFormatter.date(from: date2String(currentDate)) else { return "" }
        let calendar = Calendar.current
        let weekDay = calendar.component(.weekday, from: formatDate)
        switch weekDay {
        case 1:
            return "星期日"
        case 2:
            return "星期一"
        case 3:
            return "星期二"
        case 4:
            return "星期三"
        case 5:
            return "星期四"
        case 6:
            return "星期五"
        case 7:
            return "星期六"
        default:
            return ""
        }
    }
    
    func getLastDay() -> Date {
        let date = NSDate()
        let lastTime: TimeInterval = -(24*60*60) // 往前减去一天的秒数，昨天
        //let nextTime: TimeInterval = 24*60*60 // 这是后一天的时间，明天
        let lastDate = date.addingTimeInterval(lastTime)
        //let lastDay = dateFormatter.string(from: lastDate!)
        return lastDate as Date
    }
    
    private func showHud() {
        isShowingHUD = true
        DispatchQueue.main.asyncAfter(deadline: .now()+2){
            isShowingHUD = false
        }
    }
}

struct PTReadSchedule_Previews: PreviewProvider {
    static var previews: some View {
        PTReadSchedule()
    }
}
